import React, { createContext, useContext, useReducer } from 'react';

// 定义动作类型
type DpAction = {
  type: 'SET_DPS';
  payload: Record<string, any>;
};

// 定义状态类型
type DpState = Record<string, any>;

// 定义 reducer 函数
const dpReducer = (state: DpState, action: DpAction): DpState => {
  switch (action.type) {
    case 'SET_DPS':
      return { ...state, ...action.payload };
    default:
      return state;
  }
};

// 创建 context
const DpContext = createContext<{
  dpState: DpState;
  dispatch: React.Dispatch<DpAction>;
} | null>(null);

// 创建 Provider 组件
export const DpProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [dpState, dispatch] = useReducer(dpReducer, {});

  return (
    <DpContext.Provider value={{ dpState, dispatch }}>
      {children}
    </DpContext.Provider>
  );
};

// 创建自定义 hook 方便使用
export const useDp = () => {
  const context = useContext(DpContext);
  if (context === null) {
    throw new Error('useDp must be used within a DpProvider');
  }
  return context;
};